package com.eshipenet.shipnet.shiprpc.service;

import com.eshipenet.shipnet.ship.*;
import com.eshipenet.shipnet.ship.grpc.ShipOwnerEdge;
import com.eshipenet.shipnet.shiprpc.util.BuilderUtil;
import com.eshipenet.shipnet.shiprpc.util.FormatSql;
import com.eshipenet.shipnet.shiprpc.util.PageUtil;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.SqlQuery;
import org.apache.ignite.services.ServiceContext;
import org.json4s.JsonAST;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Option;
import squirrel.JSONQuery;

import javax.cache.Cache;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ShipOwnerServiceImp implements ShipOwnerService {
    private Logger logger = LoggerFactory.getLogger("ShipOwnerServiceImp");
    private IgniteCache<String, ShipOwner> cache ;

    public ShipOwnerServiceImp(IgniteCache<String, ShipOwner> cache) {
        this.cache = cache;
    }

    @Override
    public FindAllResult findAll(JSONQuery jsonQuery, int limit, int offset) {
        Query query = FormatSql.getFormatSql(jsonQuery);
        SqlQuery<String, ShipOwner> sql = new SqlQuery<>(com.eshipenet.shipnet.ship.ShipOwner.class, query.getSql());
        sql.setArgs(FormatSql.sqlValueToObject(query.getWhere()));
        logger.info("query ShipOwner list sql  {}",sql);
        QueryCursor<Cache.Entry<String, ShipOwner>> cursor = cache.query(sql);
        Iterator<Cache.Entry<String, ShipOwner>> iterator = cursor.iterator();

        List<ShipOwnerEdge> list = new ArrayList<>();
        //查询数量
        JSONQuery countJsonQuery = JSONQuery.apply(jsonQuery.from(),
                jsonQuery.where(),
                Option.apply(new JsonAST.JString("count(*) as count")),
                jsonQuery.includes(),
                jsonQuery.offset(),
                jsonQuery.limit());

        Query countQuery = FormatSql.getFormatSql(countJsonQuery);
        SqlFieldsQuery sqlFieldsQuery = new SqlFieldsQuery(countQuery.getSql());
        sqlFieldsQuery.setArgs(FormatSql.sqlValueToObject(countQuery.getWhere()));
        logger.info("query ShipOwner count sql  {}",sqlFieldsQuery);
        int totalCount = 0;
        try (FieldsQueryCursor<List<?>> cursor1 = cache.query(sqlFieldsQuery)) {
            for (List<?> row : cursor1) {
                totalCount = Integer.parseInt(row.get(0).toString());
            }

        }

        if(totalCount<1){
            return  new FindAllResult<>(list,totalCount,null,null,false,false);

        }

        //分页工具
        Page page = PageUtil.page(limit, totalCount, offset);
        //起点数据
        int start = page.getStartIndex();
        //结点数据
        int end = page.getEndIndex();
        //计数器
        int times = 0;

        while (iterator.hasNext()) {
            Cache.Entry<String, com.eshipenet.shipnet.ship.ShipOwner> p = iterator.next();
            if (p != null) {

                if (list.size() < limit) {
                    if (times >= start && times < end) {
                        ShipOwnerEdge ShipOwnerEdge = BuilderUtil.shipOwnerEdgeBuilder(p);
                        list.add(ShipOwnerEdge);
                    }
                } else {
                    break;
                }
            }
            times++;
        }

        return  new FindAllResult<>(list,
                totalCount,
                list.get(0).getCursor(),
                list.get(list.size()-1).getCursor(),
                page.isHasNextPage(),
                page.isHasPreviousPage());
    }

    @Override
    public ShipOwner createOne(ShipOwner shipOwner) {

        cache.put(shipOwner.getId(),shipOwner);

        shipOwner = cache.get(shipOwner.getId());

        return shipOwner;
    }

    @Override
    public ShipOwner updateOne(String id, ShipOwner shipOwner) {
        ShipOwner old = cache.get(id);

        shipOwner = new ShipOwner(
                shipOwner.getName(),
                shipOwner.getDescription(),
                shipOwner.getAvatar(),
                shipOwner.getInfo(),
                old.getCreatedAt(),
                shipOwner.getUpdatedAt(),
                id
        );


        cache.put(id, shipOwner);

        return shipOwner;
    }

    @Override
    public ShipOwner deleteOne(String id) {
        ShipOwner old = cache.get(id);
        ShipOwner shipOwner = new ShipOwner(
                old.getName(),
                old.getDescription(),
                old.getAvatar(),
                old.getInfo(),
                old.getCreatedAt(),
                old.getUpdatedAt(),
                id);

        SqlFieldsQuery query = new SqlFieldsQuery("delete from  ShipOwner  where id=? ");
        cache.query(query.setArgs(id)).getAll();
        logger.info("delete ShipOwner by id  sql  {}",query);
        return shipOwner;
    }

    @Override
    public int getCountById(String id) {

        //查询数据总数
        SqlFieldsQuery query = new SqlFieldsQuery("select count(id) from  ShipOwner where id=? ");

        query.setArgs(id);
        //数据总数
        java.util.List<?> getCount = cache.query(query).getAll().get(0);

        Object obj = getCount.get(0);

        int count = Integer.parseInt(obj.toString());

        return count;
    }

    @Override
    public void cancel(ServiceContext ctx) {

    }

    @Override
    public void init(ServiceContext ctx) throws Exception {

    }

    @Override
    public void execute(ServiceContext ctx) throws Exception {

    }
}
